package com.todod.service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.dto.EsBmwdDto;
import com.todod.dto.PublicCatalogDto;
import com.todod.mapper.CatalogManageMapper;
import com.todod.mapper.PublicCatalogMapper;
import com.todod.mapper.PublicFileAuthorityMapper;
import com.todod.mapper.PublicFileMapper;
import com.todod.model.PublicCatalog;
import com.todod.model.PublicFile;
import com.todod.model.PublicFileAuthority;
import com.todod.model.Role;
import com.todod.model.User;
import com.todod.model.UserRole;

import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

@Service
@Transactional
public class PublicCatalogService {

    @Autowired
    private PublicCatalogMapper publicCatalogMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private ElasticsearchService elasticsearchService;
    @Autowired
    private PublicFileService publicFileService;
    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private IUserRoleService iUserRoleService;
    @Autowired
    private PublicFileAuthorityMapper fileAuthorityMapper;
    @Autowired
    private PublicFileAuthorityService fileAuthorityService;
    @Autowired
    private PublicFileMapper publicFileMapper;
    @Autowired
    public CatalogManageMapper catalogManageMapper;

    /**
     * @param companyId
     * @param _userId
     * @return
     */
    public List<PublicCatalog> getListByParentId(Long companyId, Long _userId) {
        QueryWrapper<PublicCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gft_department_id", companyId);
        queryWrapper.eq("gft_createuser_id", _userId);
        queryWrapper.eq("gft_flag", "U");
        queryWrapper.eq("gft_state", "1");
        queryWrapper.orderByAsc("gft_sort_num");

        List<PublicCatalog> list = publicCatalogMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * @param _userId
     * @param type(M:部门 ; U:我的)
     * @return List<PublicCatalog>
     * @title getListInAuthorityByUserIdAndType
     * @description 根据用户id和数据类型获取当前人员的授权目录
     * @author wgb
     */
    public List<PublicCatalog> getListInAuthorityByUserIdAndType(Long _userId, String type) {
        List<PublicCatalog> returnList = new ArrayList<PublicCatalog>();

        List<String> names = new ArrayList<String>();

        List<PublicFileAuthority> listInAuthority = fileAuthorityService.getFileAuthorityByUserId(_userId);
        if (listInAuthority != null && listInAuthority.size() > 0) {
            for (PublicFileAuthority publicFileAuthority : listInAuthority) {
                PublicCatalog publicCatalog1 = publicCatalogMapper.selectById(publicFileAuthority.getFileId());
                // 文件夹 正在使用
                if (publicCatalog1 != null && publicCatalog1.getState().equalsIgnoreCase("1")) {
                    // 判断父文件夹是否处于回收站
                    String levelParent = publicCatalog1.getLevels();
                    // 判断是否正常，不处于回收站
                    Boolean flag = true;
                    if (levelParent != null && StringUtils.isNotBlank(levelParent)) {
                        String[] levelP = levelParent.split(";");
                        for (String str : levelP) {
                            Long pId = Long.valueOf(str);
                            PublicCatalog publicCatalogP = publicCatalogMapper.selectById(pId);
                            if (publicCatalogP != null && publicCatalogP.getState().equalsIgnoreCase("-1")) {
                                flag = false;
                                break;
                            }
                        }
                    } else {
                        PublicCatalog publicCatalogP = publicCatalogMapper.selectById(publicCatalog1.getId());
                        if (publicCatalogP != null && publicCatalogP.getState().equalsIgnoreCase("-1")) {
                            flag = false;
                        }
                    }
                    // 如果文件夹不处于回收站
                    if (flag) {
                        String level = publicCatalog1.getLevels();
                        if (level != null && StringUtils.isNotBlank(level)) {
                            String[] levels = level.split(";");
                            for (int i = 0; i < levels.length; i++) {
                                PublicCatalog publicCatalog2 = publicCatalogMapper.selectById(levels[i]);
                                if (!names.contains(publicCatalog2.getId().toString())) {
                                    names.add(String.valueOf(publicCatalog2.getId()));
                                    returnList.add(publicCatalog2);
                                }
                            }
                        }
                        if (!names.contains(publicCatalog1.getId().toString())) {
                            names.add(String.valueOf(publicCatalog1.getId()));
                            returnList.add(publicCatalog1);
                        }
                    }
                }

                // 文件
                PublicFile publicFile = publicFileService.selectByCodeInUse(publicFileAuthority.getFileId());
                if (publicFile != null && publicFile.getState().equalsIgnoreCase("1")) {
                    String level = publicFile.getLevel();
                    String[] levels = level.split(";");
                    PublicCatalog publicCatalog2 = publicCatalogMapper.selectById(levels[0]);

                    String level1 = publicCatalog2.getLevels();
                    if (level1 != null && StringUtils.isNotBlank(level1)) {
                        String[] levels1 = level1.split(";");
                        for (int i = 0; i < levels1.length; i++) {
                            Long pId = Long.valueOf(levels1[i]);
                            PublicCatalog publicCatalogP = publicCatalogMapper.selectById(pId);
                            // 判断文件夹是否正常，不处于回收站
                            if (publicCatalogP != null && publicCatalogP.getState().equalsIgnoreCase("-1")) {
                                break;
                            }
                            if (i == 0) {
                                PublicCatalog publicCatalog3 = publicCatalogMapper.selectById(levels1[i]);
                                if (!names.contains(publicCatalog3.getId().toString())) {
                                    names.add(String.valueOf(publicCatalog3.getId()));
                                    returnList.add(publicCatalog3);
                                }
                            } else {
                                PublicCatalog publicCatalog3 = publicCatalogMapper.selectById(levels1[i]);
                                if (!names.contains(publicCatalog3.getId().toString())) {
                                    names.add(String.valueOf(publicCatalog3.getId()));
                                    returnList.add(publicCatalog3);
                                }
                            }
                        }
                    }
                    if (!names.contains(publicCatalog2.getId().toString())) {
                        names.add(String.valueOf(publicCatalog2.getId()));
                        returnList.add(publicCatalog2);
                    }
                }
            }
        }

        return returnList;
    }

    public List<PublicCatalog> getListByFlag(String flag) {
        QueryWrapper<PublicCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gft_flag", flag);
        queryWrapper.eq("gft_state", "1");
        queryWrapper.orderByAsc("gft_sort_num");

        List<PublicCatalog> list = publicCatalogMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * @param _userId
     * @param publicCatalog
     * @throws Exception
     */
    public void saveData(Long _userId, PublicCatalog publicCatalog) throws Exception {
        publicCatalog.setId(SnowflakeIdGenerator.getId());
        publicCatalog.setState("1");
        if (publicCatalog.getParentId() != 1) {
            PublicCatalog publicCatalog1 = publicCatalogMapper.selectById(publicCatalog.getParentId());
            if (publicCatalog1.getLevels() != null) {
                publicCatalog.setLevels(publicCatalog1.getLevels() + publicCatalog1.getId() + ";");
            } else {
                publicCatalog.setLevels(publicCatalog1.getId() + ";");
            }
        }

        publicCatalog.setCreatetimeTi(LocalDateTime.now());
        publicCatalog.setCreateuserId(_userId);

        try {
            insertDoc(publicCatalog, "save");
            publicCatalogMapper.insert(publicCatalog);

            //// 赋权限
            if (publicCatalog.getFlag().equalsIgnoreCase("M")) {
                User user = iUserService.getById(_userId);
                List<Role> roleList = iRoleService.getByCompanyId(user.getDepartid());
                for (Role role : roleList) {
                    List<UserRole> list = iUserRoleService.getByRoleId(role.getId());
                    for (UserRole userRole : list) {
                        PublicFileAuthority fileAuthority = new PublicFileAuthority();
                        fileAuthority.setId(SnowflakeIdGenerator.getId());
                        fileAuthority.setFileId(publicCatalog.getId());
                        fileAuthority.setUserId(userRole.getUserId());
                        fileAuthority.setCreateuserId(_userId);
                        fileAuthority.setCreatetimeTi(LocalDateTime.now());
                        fileAuthorityMapper.insert(fileAuthority);
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("目录保存失败，请稍后再试");
        }
    }

    /**
     * @param _userId
     * @param publicCatalog
     * @throws Exception
     */
    public void editData(Long _userId, PublicCatalog publicCatalog) throws Exception {
        PublicCatalog publicCatalog1 = publicCatalogMapper.selectById(publicCatalog.getId());

        publicCatalog.setCreatetimeTi(publicCatalog1.getCreatetimeTi());
        publicCatalog.setCreateuserId(publicCatalog1.getCreateuserId());
        publicCatalog.setModifytimeTi(LocalDateTime.now());
        publicCatalog.setModifyuserId(_userId);

        try {
            insertDoc(publicCatalog, "edit");
            publicCatalogMapper.updateById(publicCatalog);

            QueryWrapper<PublicFileAuthority> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("gfa_file_id", publicCatalog.getId());

            List<PublicFileAuthority> authList = fileAuthorityMapper.selectList(queryWrapper);
            for (PublicFileAuthority fileAuthority : authList) {
                fileAuthorityMapper.deleteById(fileAuthority.getId());
            }

            //// 赋权限
            if (publicCatalog.getFlag().equalsIgnoreCase("M")) {
                User user = iUserService.getById(_userId);
                List<Role> roleList = iRoleService.getByCompanyId(user.getDepartid());
                for (Role role : roleList) {
                    List<UserRole> list = iUserRoleService.getByRoleId(role.getId());
                    for (UserRole userRole : list) {
                        PublicFileAuthority fileAuthority = new PublicFileAuthority();
                        fileAuthority.setId(SnowflakeIdGenerator.getId());
                        fileAuthority.setFileId(publicCatalog.getId());
                        fileAuthority.setUserId(userRole.getUserId());
                        fileAuthority.setCreateuserId(_userId);
                        fileAuthority.setCreatetimeTi(LocalDateTime.now());
                        fileAuthorityMapper.insert(fileAuthority);
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("目录保存失败，请稍后再试");
        }
    }

    /**
     * @param code
     * @return
     */
    public Map<String, Object> getInfo(Long code) {
        Map<String, Object> map = new HashMap<>();
        PublicCatalogDto publicCatalog = publicCatalogMapper.getInfo(code);

        map.put("publicCatalog", publicCatalog);
        return map;
    }

    /**
     * @param departid
     * @param parentId
     * @return Integer
     * @Title: getSortNumByDepartIdAndParentId
     * @Description:根据部门id和父id获得目录排序
     * @author: dyl
     * @date 2020-03-15
     */
    public Integer getSortNumByDepartIdAndParentId(Long departid, Long parentId) {
        return publicCatalogMapper.getSortNumByDepartIdAndParentId(departid, parentId);
    }

    /**
     * @param code
     * @return
     */
    public PublicCatalog getCatalogByCode(Long code) {
        QueryWrapper<PublicCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gft_id", code);

        PublicCatalog publicCatalog = publicCatalogMapper.selectOne(queryWrapper);
        return publicCatalog;
    }

    public List<PublicCatalog> getListByCompanyIdAndType(Long companyId, String type, Long _userId, String parentId) {
        QueryWrapper<PublicCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gft_flag", type);
        queryWrapper.eq("gft_parent_id", parentId);
        if (type != null && !type.equalsIgnoreCase("M")) {
            queryWrapper.eq("gft_department_id", companyId);
        }
        if (_userId != null) {
            queryWrapper.eq("gft_createuser_id", _userId);
        }

        List<PublicCatalog> list = publicCatalogMapper.selectList(queryWrapper);
        return list;
    }

    public void insertDoc(PublicCatalog publicCatalog, String flag) throws Exception {
        if (publicCatalog.getParentId() != 1l && publicCatalog.getParentId() != null) {
            EsBmwdDto bmwdDto = new EsBmwdDto();
            String gftName = "";
            PublicCatalog publicCatalog0 = publicCatalogMapper.selectById(publicCatalog.getParentId());
            gftName = publicCatalog0.getTypeName() + gftName;

            if (publicCatalog0.getParentId() != 1l && publicCatalog0.getParentId() != null) {
                PublicCatalog a = new PublicCatalog();
                Long gftId = publicCatalog0.getParentId();
                a.setId(gftId);
                List<PublicCatalog> list = publicCatalogMapper.selectList(null);
                for (int i = 0; i < list.size(); i++) {
                    if (a.getId() != 1l && a.getId() != null) {
                        Optional<PublicCatalog> any = list.stream().filter((x) -> x.getId().equals(a.getId()))
                                .findAny();
                        if (any.isPresent()) {
                            gftName = any.get().getTypeName() + "->" + gftName;
                            gftId = any.get().getParentId();
                            a.setId(gftId);
                        }
                    }
                }
            }

            bmwdDto.setId(publicCatalog.getId());
            bmwdDto.setDepartmentId(publicCatalog.getDepartmentId());
            bmwdDto.setGftId(publicCatalog.getParentId());
            bmwdDto.setGftName(gftName);
            bmwdDto.setFileName(publicCatalog.getTypeName());
            bmwdDto.setFileLabel("");
            bmwdDto.setSuffix("文件夹");
            bmwdDto.setFileSize("0");
            bmwdDto.setType(publicCatalog.getFlag());
            bmwdDto.setState(publicCatalog.getState());
            bmwdDto.setSortNum(publicCatalog.getSortNum());
            bmwdDto.setPaixu("paixu1");
            bmwdDto.setCreatetimeTi(publicCatalog.getCreatetimeTi().toString().replaceAll("T", " "));
            bmwdDto.setCreateuserId(publicCatalog.getCreateuserId());
            bmwdDto.setContent("");
            bmwdDto.setDownloads(0);
            bmwdDto.setViews(0);

            User user = iUserService.getById(publicCatalog.getCreateuserId());
            bmwdDto.setUserName(user.getNickName());

            bmwdDto.setUrl("");

            if (flag.equalsIgnoreCase("save")) {
                BulkRequest bulkRequest = new BulkRequest();
                if (bmwdDto.getType().equalsIgnoreCase("M")) {
                    bulkRequest.add(new IndexRequest("bmwd").id(String.valueOf(bmwdDto.getId()))
                            .source(JSON.toJSONString(bmwdDto), XContentType.JSON));
                } else {
                    bulkRequest.add(new IndexRequest("grwd").id(String.valueOf(bmwdDto.getId()))
                            .source(JSON.toJSONString(bmwdDto), XContentType.JSON));
                }

                try {
                    BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
                    if (bulkResponse.hasFailures()) {
                        System.out.println(bulkResponse.buildFailureMessage());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new Exception("目录保存失败，请稍后再试");
                }
            } else {
                try {
                    if (bmwdDto.getType().equalsIgnoreCase("M")) {
                        elasticsearchService.updateDocs("bmwd", "_doc", String.valueOf(bmwdDto.getId()),
                                (JSONObject) JSONObject.toJSON(bmwdDto));
                    } else {
                        elasticsearchService.updateDocs("grwd", "_doc", String.valueOf(bmwdDto.getId()),
                                (JSONObject) JSONObject.toJSON(bmwdDto));
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param _userId
     * @param publicCatalog
     * @return
     * @throws Exception
     * @Title: copyData
     * @Description:复制文件夹数据
     * @author: wgb
     * @date 2020-06-26
     */
    public void copyData(Long _userId, PublicCatalog publicCatalog) throws Exception {
        // 源数据
        PublicCatalog publicCatalogNew = publicCatalogMapper.selectById(publicCatalog.getId());

        Long cataLogId = publicCatalogNew.getId();
//		Long cataLogDepartmentId = publicCatalogNew.getDepartmentId();
        // 在获取数据基础上，修改id、父id、排序、人员、时间
        publicCatalogNew.setId(SnowflakeIdGenerator.getId());
        publicCatalogNew.setParentId(publicCatalog.getParentId());
//		publicCatalogNew.setDepartmentId(publicCatalog.getDepartmentId());
        Integer sortNum = getSortNumByDepartIdAndParentId(publicCatalogNew.getDepartmentId(),
                publicCatalogNew.getParentId());
        publicCatalogNew.setSortNum(sortNum);
        publicCatalogNew.setCreateuserId(_userId);
        publicCatalogNew.setCreatetimeTi(LocalDateTime.now());
        publicCatalogNew.setModifyuserId(_userId);
        publicCatalogNew.setModifytimeTi(LocalDateTime.now());

        // 源数据
        PublicCatalog publicCatalogNew1 = publicCatalogMapper.selectById(publicCatalog.getParentId());
        if (!publicCatalogNew1.getParentId().equals(1l)) {
            publicCatalogNew.setLevels(publicCatalogNew1.getLevels() + publicCatalog.getParentId() + ";");
        } else {
            publicCatalogNew.setLevels(publicCatalog.getParentId() + ";");
        }

        try {
            insertDoc(publicCatalogNew, "save");

            publicCatalogMapper.insert(publicCatalogNew);

            // 复制文件夹下面的文件夹和文件
            if (this.getListCatalogByParentId(cataLogId).size() > 0
                    || publicFileService.getListFileByParentId(cataLogId).size() > 0) {
                copyDataInChildren(_userId, cataLogId, publicCatalogNew.getId());
            }

            if (publicCatalogNew.getFlag().equalsIgnoreCase("M")) {
                PublicFileAuthority fileAuthority = new PublicFileAuthority();
                fileAuthority.setId(SnowflakeIdGenerator.getId());
                fileAuthority.setFileId(publicCatalogNew.getId());
                fileAuthority.setUserId(_userId);
                fileAuthority.setCreateuserId(_userId);
                fileAuthority.setCreatetimeTi(LocalDateTime.now());
                fileAuthorityMapper.insert(fileAuthority);
            }
        } catch (IOException e) {
            throw new Exception("目录保存失败，请稍后再试");
        }
    }

    /**
     * @param _userId
     * @param parentId
     * @param id
     * @return
     * @Title: copyDataInChildren
     * @Description:复制文件夹及子文件数据
     * @author: wgb
     * @date 2020-06-26
     */
    public void copyDataInChildren(Long _userId, Long parentId, Long id) {
        List<PublicCatalog> listCatalog = this.getListCatalogByParentId(parentId);
        listCatalog.forEach(x -> {
            Long cataLogId = x.getId();

            x.setId(SnowflakeIdGenerator.getId());
            x.setParentId(id);
            Integer sortNum = getSortNumByDepartIdAndParentId(x.getDepartmentId(), x.getParentId());
            x.setSortNum(sortNum);
            x.setCreateuserId(_userId);
            x.setCreatetimeTi(LocalDateTime.now());
            x.setModifyuserId(_userId);
            x.setModifytimeTi(LocalDateTime.now());

            // 源数据
            PublicCatalog publicCatalogNew1 = publicCatalogMapper.selectById(x.getParentId());
            if (publicCatalogNew1 != null) {
                if (!publicCatalogNew1.getParentId().equals(1l)) {
                    x.setLevels(publicCatalogNew1.getLevels() + x.getParentId() + ";");
                } else {
                    x.setLevels(x.getParentId() + ";");
                }

                try {
                    insertDoc(x, "save");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            publicCatalogMapper.insert(x);

            if (this.getListCatalogByParentId(cataLogId).size() > 0
                    || publicFileService.getListFileByParentId(cataLogId).size() > 0) {
                copyDataInChildren(_userId, cataLogId, x.getId());
            }

            if (x.getFlag().equalsIgnoreCase("M")) {
                PublicFileAuthority fileAuthority = new PublicFileAuthority();
                fileAuthority.setId(SnowflakeIdGenerator.getId());
                fileAuthority.setFileId(x.getId());
                fileAuthority.setUserId(_userId);
                fileAuthority.setCreateuserId(_userId);
                fileAuthority.setCreatetimeTi(LocalDateTime.now());
                fileAuthorityMapper.insert(fileAuthority);
            }
        });
//		List<PublicFile> listFile = publicFileService.getListFileByParentId(parentId);
//		listFile.forEach(x -> {
//			x.setGftId(id);
//			publicFileService.copyData(_userId, x);
//		});
    }

    /**
     * @param _userId
     * @param publicCatalog
     * @return
     * @throws Exception
     * @Title: moveData
     * @Description:移动文件夹数据
     * @author: wgb
     * @date 2020-06-26
     */
    public void moveData(Long _userId, PublicCatalog publicCatalog) throws Exception {
        // 源数据
        PublicCatalog publicCatalogNew = publicCatalogMapper.selectById(publicCatalog.getId());
        // 在获取数据基础上，修改父id、排序、修改人员及时间
        publicCatalogNew.setParentId(publicCatalog.getParentId());
//		publicCatalogNew.setDepartmentId(publicCatalog.getDepartmentId());
        Integer sortNum = getSortNumByDepartIdAndParentId(publicCatalogNew.getDepartmentId(),
                publicCatalogNew.getParentId());
        publicCatalogNew.setSortNum(sortNum);
        publicCatalogNew.setModifyuserId(_userId);
        publicCatalogNew.setModifytimeTi(LocalDateTime.now());

        // 源数据
        PublicCatalog publicCatalogNew1 = publicCatalogMapper.selectById(publicCatalog.getParentId());
        if (!publicCatalogNew1.getParentId().equals(1l)) {
            publicCatalogNew.setLevels(publicCatalogNew1.getLevels() + publicCatalog.getParentId() + ";");
        } else {
            publicCatalogNew.setLevels(publicCatalog.getParentId() + ";");
        }

        publicCatalogMapper.updateById(publicCatalogNew);

        try {
            insertDoc(publicCatalogNew, "edit");
        } catch (IOException e) {
            throw new Exception("目录保存失败，请稍后再试");
        }
    }

    /**
     * @param parentId
     * @return List<PublicCatalog>
     * @Title: getListCatalogBparentId
     * @Description:根据parentId获取子文件夹
     * @author: wgb
     * @date 2020-06-26
     */
    public List<PublicCatalog> getListCatalogByParentId(Long parentId) {
        QueryWrapper<PublicCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gft_parent_id", parentId);
        queryWrapper.eq("gft_state", "1");
        queryWrapper.orderByAsc("gft_sort_num");
        return publicCatalogMapper.selectList(queryWrapper);
    }

    /**
     * @param _userId
     * @param id
     * @param status
     * @return List<PublicCatalog>
     * @Title: deleteInLogic
     * @Description:根据id修改文件状态
     * @author: wgb
     * @date 2020-06-26
     */
    public void deleteInLogic(Long _userId, Long id, String status) {
        // 源数据
        PublicCatalog publicCatalogNew = publicCatalogMapper.selectById(id);
        if (publicCatalogNew != null) {
            publicCatalogNew.setState(status);
            publicCatalogNew.setModifyuserId(_userId);
            publicCatalogNew.setModifytimeTi(LocalDateTime.now());
            publicCatalogMapper.updateById(publicCatalogNew);

            try {
                insertDoc(publicCatalogNew, "edit");

                // 更改子文件夹及文件状态
                deleteIn(_userId, id, status);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            List<PublicFileAuthority> list = fileAuthorityService
                    .getAuthorityByFileIdAndUserId(publicCatalogNew.getId(), _userId);
            for (PublicFileAuthority publicFileAuthority : list) {
                fileAuthorityMapper.deleteById(publicFileAuthority.getId());
            }
        } else {
            try {
                publicFileService.updateUserAndStatus(_userId, id, status);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void deleteIn(Long _userId, Long id, String status) {
        // 删除当前文件夹下面的文件夹和文件
        if (this.getListCatalogByParentId(id).size() > 0 || publicFileService.getListFileByParentId(id).size() > 0) {
            // 获取所有子节点
            Map<String, Object> map = getChildren(id);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (entry.getKey().equalsIgnoreCase("listCatalog")) {
                    List<PublicCatalog> listCatalog = (List<PublicCatalog>) entry.getValue();
                    listCatalog.forEach(x -> {
                        x.setState(status);
                        x.setModifyuserId(_userId);
                        x.setModifytimeTi(LocalDateTime.now());
                        try {
                            insertDoc(x, "edit");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    });
                }
                if (entry.getKey().equalsIgnoreCase("listFile")) {
                    List<PublicFile> listFile = (List<PublicFile>) entry.getValue();
                    listFile.forEach(x -> {
                        x.setState(status);
                        x.setModifyuserId(_userId);
                        x.setModifytimeTi(LocalDateTime.now());
                        publicFileService.insertDoc(x, "edit");
                    });
                }
            }
        }
    }

    /**
     * @param id
     * @return Map<String, Object>
     * @Title: deleteAllInCatalog
     * @Description:删除当前文件夹下面的文件夹和文件
     * @author: wgb
     * @date 2020-06-26
     */
    @SuppressWarnings("unchecked")
    public void deleteAllInCatalog(Long _userId, Long id) {
        // 删除当前文件夹下面的文件夹和文件
        if (this.getListCatalogByParentId(id).size() > 0 || publicFileService.getListFileByParentId(id).size() > 0) {
            // 获取所有子节点
            Map<String, Object> map = getChildren(id);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
                if (entry.getKey().equalsIgnoreCase("listCatalog")) {
                    List<PublicCatalog> listCatalog = (List<PublicCatalog>) entry.getValue();
                    listCatalog.forEach(x -> {
                        // 删除文件夹
                        publicCatalogMapper.deleteById(x.getId());
                        // 删除文件夹权限
//						fileAuthorityService.deleteAuthByFileIdAndType(x.getId(), "1");

//						if (x.getFlag().equalsIgnoreCase("M")) {
//							elasticsearchService.deleteDocs("bmwd", "_doc", String.valueOf(x.getId()),
//									(JSONObject) JSONObject.toJSON(x));
//						} else {
//							elasticsearchService.deleteDocs("grwd", "_doc", String.valueOf(x.getId()),
//									(JSONObject) JSONObject.toJSON(x));
//						}
                    });
                }
                if (entry.getKey().equalsIgnoreCase("listFile")) {
                    List<PublicFile> listFile = (List<PublicFile>) entry.getValue();
                    listFile.forEach(x -> {
                        // 删除文件
                        publicFileService.deleteById(x.getId());

                        // 删除权限
//						fileAuthorityService.deleteAuthByFileIdAndType(x.getId(), "2");

//						if (x.getType().equalsIgnoreCase("M")) {
//							elasticsearchService.deleteDocs("bmwd", "_doc", String.valueOf(x.getId()),
//									(JSONObject) JSONObject.toJSON(x));
//						} else {
//							elasticsearchService.deleteDocs("grwd", "_doc", String.valueOf(x.getId()),
//									(JSONObject) JSONObject.toJSON(x));
//						}
                    });
                }

            }
        }
    }

    /**
     * @param parentId
     * @return Map<String, Object>
     * @Title: getChildren
     * @Description:根据父id获取子文件夹和子文件
     * @author: wgb
     * @date 2020-06-26
     */
    public Map<String, Object> getChildren(Long parentId) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<PublicCatalog> listCatalog = this.getListCatalogByParentId(parentId);
        List<PublicFile> listFile = publicFileService.getListFileByParentId(parentId);
        if (listFile.size() > 0) {
            map.put("listFile", listFile);
        }
        if (listCatalog.size() > 0) {
            map.put("listCatalog", listCatalog);
            listCatalog.forEach(x -> {
                if (this.getListCatalogByParentId(x.getId()).size() > 0
                        || publicFileService.getListFileByParentId(x.getId()).size() > 0) {
                    map.put("children", getChildren(x.getId()));
                }

            });
        }
        return map;
    }

    /**
     * @param id
     * @return
     * @Title: deleteAllInCatalogOrFile
     * @Description:根据id删除子文件夹和子文件
     * @author: wgb
     * @date 2020-06-26
     */
    public void deleteAllInCatalogOrFile(Long _userId, Long id) {
        // 源数据
        PublicCatalog publicCatalogNew = publicCatalogMapper.selectById(id);
        if (publicCatalogNew != null) {
            publicCatalogMapper.deleteById(id);

            if (publicCatalogNew.getFlag().equalsIgnoreCase("M")) {
                elasticsearchService.deleteDoc("bmwd", "_doc", String.valueOf(publicCatalogNew.getId()),
                        (JSONObject) JSONObject.toJSON(publicCatalogNew));
            } else {
                elasticsearchService.deleteDoc("grwd", "_doc", String.valueOf(publicCatalogNew.getId()),
                        (JSONObject) JSONObject.toJSON(publicCatalogNew));
            }
        } else {
            PublicFile publicFile = publicFileMapper.selectById(id);
            publicFileService.deleteById(id);

            if (publicFile.getType().equalsIgnoreCase("M")) {
                elasticsearchService.deleteDoc("bmwd", "_doc", String.valueOf(publicFile.getId()),
                        (JSONObject) JSONObject.toJSON(publicFile));
            } else {
                elasticsearchService.deleteDoc("grwd", "_doc", String.valueOf(publicFile.getId()),
                        (JSONObject) JSONObject.toJSON(publicFile));
            }
        }
        // 删除子文件夹及文件
        this.deleteAllInCatalog(_userId, id);
    }

    /**
     * @param _userId
     * @param fileId
     * @return Boolean true:不是当前用户 false:是当前用户
     * @Title: createorIsUserMOU
     * @Description:判断目录或文件是否是当前用户创建
     * @author: wgb
     * @date 2020-06-30
     */
    public Boolean createorIsUserMOU(Long _userId, Long fileId) {
        Boolean flag = true;
        PublicCatalog publicCatalog = publicCatalogMapper.selectById(fileId);
        PublicFile PublicFile = publicFileService.selectByCodeInUse(fileId);
        if (publicCatalog != null || PublicFile != null) {
            if (publicCatalog != null
                    && publicCatalog.getCreateuserId().toString().equalsIgnoreCase(_userId.toString())) {
                flag = false;
            } else {
                if (PublicFile != null
                        && PublicFile.getCreateuserId().toString().equalsIgnoreCase(_userId.toString())) {
                    flag = false;
                }
            }
        }
        return flag;
    }

    /**
     * @param parentId
     * @return List<PublicCatalog>
     * @Title: getSelfAndChildren
     * @Description:根据id获取当前节点及其子文件夹和子文件-树状结构
     * @author: wgb
     * @date 2020-06-26
     */
    public List<PublicCatalog> getSelfAndChildren(Long parentId) {
        List<PublicCatalog> listCatalog = new ArrayList<PublicCatalog>();
        listCatalog.add(getSelf(parentId));
        return listCatalog;
    }

    /**
     * @param parentId
     * @return PublicCatalog
     * @Title: getSelf
     * @Description:根据id获取当前节点及其子文件夹和子文件
     * @author: wgb
     * @date 2020-06-26
     */
    public PublicCatalog getSelf(Long parentId) {
        PublicCatalog publicCatalog = this.getCatalogByCode(parentId);
        List<PublicFile> listFile = new ArrayList<PublicFile>();
        if (publicCatalog != null) {
            listFile = publicFileService.getListFileByParentId(parentId);
            publicCatalog.setListFile(listFile);
            publicCatalog.setChildren2(getChildren2(parentId));
        } else {
            publicCatalog = new PublicCatalog();
            PublicFile file = publicFileService.selectByCodeInUse(parentId);
            listFile.add(file);
            publicCatalog.setListFile(listFile);
        }

        return publicCatalog;
    }

    /**
     * @param parentId
     * @return List<PublicCatalog>
     * @Title: getChildren2
     * @Description:根据父id获取子文件夹和子文件-树状结构
     * @author: wgb
     * @date 2020-06-26
     */
    public List<PublicCatalog> getChildren2(Long parentId) {
        List<PublicCatalog> listCatalog = this.getListCatalogByParentId(parentId);
        if (listCatalog.size() > 0) {
            listCatalog.forEach(x -> {
                if (this.getListCatalogByParentId(x.getId()).size() > 0
                        || publicFileService.getListFileByParentId(x.getId()).size() > 0) {
                    List<PublicFile> listFile = publicFileService.getListFileByParentId(x.getId());
                    x.setListFile(listFile);
                    x.setChildren2(getChildren2(x.getId()));
                }
            });
        }
        return listCatalog;
    }

    public Map<String, Object> getOnlyChildren(Long parentId) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<PublicCatalog> listCatalog = this.getListCatalogByParentId(parentId);
        listCatalog.forEach(x -> {
            if (this.getListCatalogByParentId(x.getId()).size() > 0
                    || publicFileService.getListFileByParentId(x.getId()).size() > 0) {
                map.put("children", getOnlyChildren(x.getId()));

            }

        });
        List<PublicFile> listFile = publicFileService.getListFileByParentId(parentId);
        if (listFile.size() > 0) {
            map.put("listFile", listFile);
        }
        return map;
    }

    /**
     * @param _userId
     * @param companyId
     * @param type(M:部门 ; U:我的)
     * @return List<PublicCatalog>
     * @title getListInAuthorityByUserIdAndType
     * @description 根据用户id和数据类型获取当前人员的授权目录
     * @author wgb
     */
    public List<PublicCatalog> getListByUserIdAndType(Long _userId, String type, Long companyId) {
        List<PublicCatalog> returnList = new ArrayList<PublicCatalog>();

        List<String> names = new ArrayList<String>();

//		QueryWrapper<PublicCatalog> queryWrapper = new QueryWrapper<>();
//		queryWrapper.eq("gft_department_id", companyId);
//		queryWrapper.eq("gft_flag", type);
//		queryWrapper.eq("gft_state", "1");
//		queryWrapper.orderByAsc("gft_sort_num");
//
//		List<PublicCatalog> list = publicCatalogMapper.selectList(queryWrapper);

        List<PublicCatalog> list = publicCatalogMapper.getFileAuthorityByUserId(_userId);
        for (PublicCatalog publicCatalog : list) {
            String levelParent = publicCatalog.getLevels();
            if (levelParent != null && StringUtils.isNotBlank(levelParent)) {
                String[] levelP = levelParent.split(";");
                if (levelP.length == 1) {
                    if (!names.contains(publicCatalog.getId().toString())) {
                        names.add(String.valueOf(publicCatalog.getId()));
                        returnList.add(publicCatalog);
                    }
                }
            } else {
                if (!names.contains(publicCatalog.getId().toString())) {
                    names.add(String.valueOf(publicCatalog.getId()));
                    returnList.add(publicCatalog);
                }
            }
        }

        return returnList;
    }

    public List<PublicCatalog> getListByUserIdAndTypeAndParentId(Long _userId, String type, Long companyId,
                                                                 Long parentId) {
        List<PublicCatalog> returnList = new ArrayList<PublicCatalog>();

        List<String> names = new ArrayList<String>();

        QueryWrapper<PublicCatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gft_department_id", companyId);
        queryWrapper.eq("gft_parent_id", parentId);
        queryWrapper.eq("gft_flag", type);
        queryWrapper.eq("gft_state", "1");
        queryWrapper.orderByAsc("gft_sort_num");

        List<PublicCatalog> list = publicCatalogMapper.selectList(queryWrapper);
        for (PublicCatalog publicCatalog : list) {
            List<PublicFileAuthority> list1 = fileAuthorityService.getAuthorityByFileIdAndUserId(publicCatalog.getId(),
                    _userId);
            if (list1 != null && list1.size() > 0) {
                if (!names.contains(publicCatalog.getId().toString())) {
                    names.add(String.valueOf(publicCatalog.getId()));
                    returnList.add(publicCatalog);
                }
            }
        }

        return returnList;
    }

}
